import { reqregister } from "../../http/api";
import { Toast } from "antd-mobile";
//初始值
const initState={
    user:{
        phone:"",
        nickname:"",
        password:""
    }
}

//types 
const TYPES={
    //修改user
    REGISTER_CHANGE_USER:"REGISTER_CHANGE_USER"
}

//修改state的reducer
const reducer=(state=initState,action)=>{
    switch(action.type){
        //修改user的reducer
        case TYPES.REGISTER_CHANGE_USER:
            //action={type:~,key:"phone",value:""}
            return {
                ...state,
                user:{
                    ...state.user,
                    [action.key] : action.value
                }
            }
        default:
            return state
    }
}

//actionCreators 
export const actions={
    //修改user的action
    changeUser:(key,value)=>({
        type:TYPES.REGISTER_CHANGE_USER,
        key,
        value
    }),
    //注册的请求
    reqRegister:(push)=>{
        return (dispatch,getState)=>{
            let {
                register:{
                    user
                }
            }=getState();
            //请求
            reqregister(user).then(res=>{
                if(res.data.code==200){
                    Toast.show({
                        icon: 'success',
                        content: '注册成功',
                    });
                    push("/login")
                }
            })
        }
    }
}

//导出数据
export const getUser = state =>state.register.user

//导出reducer 
export default reducer